package com.msb.smsgateway.config;

import com.msb.common.constart.RabbitMQConstants;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: lmf
 * @Create: 2025/3/21 10:08
 * @module
 */
@Configuration
public class RabbitMQConfig {

    private final int TTL = 10000;
    private final String FANOUT_ROUTING_KEY = "";

    // 声明死信队列，需要准备普通交换机，普通队列，死信交换机，死信队列

    /**
     * 普通交换机
     */
    @Bean
    public Exchange normalExchange() {
        return ExchangeBuilder.fanoutExchange(RabbitMQConstants.SMS_GATEWAY_NORMAL_EXCHANGE).build();
    }

    /**
     * 普通队列
     */
    @Bean
    public Queue normalQueue() {
        return QueueBuilder.durable(RabbitMQConstants.SMS_GATEWAY_NORMAL_QUEUE)
                // 设置队列过期时间
                .withArgument("x-message-ttl", TTL)
                // 设置死信队列 (过期后存放的交换机)
                .withArgument("x-dead-letter-exchange", RabbitMQConstants.SMS_GATEWAY_DEAD_EXCHANGE)
                // 设置死信路由键
                .withArgument("x-dead-letter-routing-key", FANOUT_ROUTING_KEY)
                .build();
    }

    /**
     * 绑定
     */
    @Bean
    public Binding normalBinding(Exchange normalExchange, Queue normalQueue){
        return BindingBuilder.bind(normalQueue).to(normalExchange).with("").noargs();
    }

    /**
     * 死信交换机
     */
    @Bean
    public Exchange deadExchange() {
        return ExchangeBuilder.fanoutExchange(RabbitMQConstants.SMS_GATEWAY_DEAD_EXCHANGE).build();
    }

    /**
     * 死信队列
     */
    @Bean
    public Queue deadQueue(){
        return QueueBuilder.durable(RabbitMQConstants.SMS_GATEWAY_DEAD_QUEUE).build();
    }

    /**
     * 死信绑定
     */
    @Bean
    public Binding deadBinding(Exchange deadExchange, Queue deadQueue){
        return BindingBuilder.bind(deadQueue).to(deadExchange).with("").noargs();
    }


    /**
     * 定义单独的配置类，，在使用时指定对应的配置类
     */
    @Bean
    public SimpleRabbitListenerContainerFactory gatewayContainerFactory(ConnectionFactory connectionFactory,
                                                                        SimpleRabbitListenerContainerFactoryConfigurer configurer) {
        SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory =
                new SimpleRabbitListenerContainerFactory();
        simpleRabbitListenerContainerFactory.setConcurrentConsumers(5);
        simpleRabbitListenerContainerFactory.setPrefetchCount(10);
        simpleRabbitListenerContainerFactory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        configurer.configure(simpleRabbitListenerContainerFactory, connectionFactory);
        return simpleRabbitListenerContainerFactory;
    }


}
